package com.sky.service.common.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.ParamsIllegalException;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author ghy
 * @version 1.0.1
 * @date 2024-02-22 15:53:58
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    public Result<List<Dish>> findByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishList = dishMapper.selectByNameStatusCategoryId(dish);
        return Result.success(dishList);
    }

    @Override
    @Transactional
    public Result<String> updateWithFlavors(DishDTO dishDTO) {
        // 一.校验参数

        // 二.处理业务
        // 1.修改菜品基本数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        // 2.修改菜品品味数据
        // 2.1 删除关联数据
        dishFlavorMapper.deleteByDishId(dish.getId());
        // 2.2 增加关联数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.insertBatch(flavors);
        // 三.封装数据
        return Result.success();
    }

    @Override
    public Result<DishVO> findByIdWithFlavors(Long id) {
        // 一.校验参数

        // 二.处理业务
        // 1.查询菜品基本数据及口味数据
        DishVO dishVO = dishMapper.selectDishAndFlavorsById(id);
        // 三.封装数据
        return Result.success(dishVO);
    }

    /**
     * 菜品批量删除
     *
     * @param ids
     */
    @Transactional//事务
    public void deleteBatch(List<Integer> ids) {
        //查询删除的菜品是否有在起售中的
        Integer count = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if(count>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //查询删除的菜品是否有被套餐关联的
        Integer count2= setmealDishMapper.selectCountByDishIds(ids);
        if(count2>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //都没有，删除菜品的口味信息
        dishFlavorMapper.deleteByDishIds(ids);

        //删除菜品信息
        dishMapper.deleteByIds(ids);
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);//后绪步骤实现
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public Result<String> addWithFlavors(DishDTO dishDTO) {
        // 一.校验参数
        if(Objects.isNull(dishDTO)
            || Objects.isNull(dishDTO.getCategoryId())
            || StringUtils.isBlank(dishDTO.getName())
            || Objects.isNull(dishDTO.getPrice())
            || StringUtils.isBlank(dishDTO.getImage())){
            throw new ParamsIllegalException("参数非法");
        }
        // 二.处理业务
        //0.菜品名称去重校验
        Long count = dishMapper.countByName(dishDTO.getName());
        if(count > 0) {
            throw new BaseException("菜品名称已存在，请更换！！");
        }
        //1.保存菜品数据到菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        // 2.保存菜品与口味数据到菜品口味表
        // 为每个口味都设置菜品ID
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dish.getId());
        });
        dishFlavorMapper.insertBatch(flavors);
        // 三.封装数据
        return Result.success();
    }
}
